'use strict';
const dayjs = require("dayjs");

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;
  
  const Permissions = app.model.define(
    'Permissions',
    {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      name: { type: STRING(50), allowNull: false },
      code: { type: STRING(50), allowNull: false, unique: true },
      description: { type: STRING(255) },
      create_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      update_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      }
    },
    {
      tableName: 'permissions',
      timestamps: true,
      createdAt: 'create_time',
      updatedAt: 'update_time'
    }
  );

  Permissions.associate = function() {
    app.model.Permissions.belongsToMany(app.model.Roles, { 
      through: app.model.RolePermissions,
      foreignKey: 'permission_id',
      otherKey: 'role_id',
      as: 'roles'
    });
  };

  return Permissions;
};
